<template>
  <div>
      <div>
        <!--    功能-->
        <div style="margin-left:5px;float:left">
            <el-button type="warning" plain @click="add" v-show="user!=null">新增</el-button>
            <el-button type="primary" plain >导入</el-button>
            <el-button type="primary" plain >导出</el-button>
        </div>
        <!--    搜索区域-->
        <div style="float:right;margin-right:25px">
            <el-input v-model="search" placeholder="请输入关键字" style="width: 80%" clearable></el-input>
            <!-- <el-button style="margin-left: 5px; background-color: #5defc1; color: white" @click="selectIts" plain>查询</el-button> -->
        </div>
      </div>
    <el-table
    :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
    style="width: 100%"
    stripe
    v-loading="loading"
    >
      <el-table-column
        label="Date"
        prop="createTime"
        :formatter="formatData"
        sortable>
      </el-table-column>
      <el-table-column
        label="商品名"
        prop="name">
      </el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image 
              style="width: 50px; height: 50px"
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="单价"
        prop="price">
      </el-table-column>
      <el-table-column
        label="库存"
        prop="stock">
      </el-table-column>
      <el-table-column
        label="品牌名"
        prop="brand.name">
      </el-table-column>
      <el-table-column
        label="商品类型"
        prop="category.name">
      </el-table-column>
      <el-table-column
        label="商品状态">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1">上架</span>
          <span v-else>下架</span>
        </template>
      </el-table-column>
      <!-- if和else -->
      <el-table-column
      v-if="user!=null"
        label="操作">
        <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column
      v-else
        label="操作"
        align="center">
        <template slot-scope="scope">
            <el-popconfirm
            title="确定上架该商品吗？"
            @confirm="handleUnBan(scope.row)"
            >
              <el-button
              slot="reference"
              size="mini"
              type="success"
              v-show="scope.row.state == 1?false:true">上架</el-button>
                            <!-- :disabled="scope.row.state == 1?true:false" -->
            </el-popconfirm>
            <el-popconfirm
            title="确定下架该商品吗？"
            @confirm="handleBan(scope.row)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="danger"
                v-show="scope.row.state == 1?true:false">下架</el-button>
                                <!-- :disabled="scope.row.state == 1?false:true" -->
            </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <div class="pagination" style="float:left">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
        <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="30%">
        <el-form ref="form" :model="form"  label-width="120px" size="small">
            <el-form-item label="商品名" >
                <el-input v-model="form.name" style="width:60%;"></el-input>
            </el-form-item>
            <el-form-item label="单价">
                <el-input v-model="form.price" style="width:60%;"></el-input>
            </el-form-item>
            <el-form-item label="库存">
                <el-input v-model="form.stock" style="width:60%;"></el-input>
            </el-form-item>
            <el-form-item label="品牌名">
              <!-- 注意品牌id -->
                <el-select style="width:60%;" v-model="form.brand" filterable placeholder="请选择">
                    <el-option
                    v-for="item in brands"
                    :key="item.id"
                    :label="item.name"
                    :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="类型">
                <el-select  style="width:60%;" v-model="form.category" filterable placeholder="请选择">
                    <el-option
                    v-for="item in categories"
                    :key="item.id"
                    :label="item.name"
                    :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品状态">
              <el-radio v-model="form.state" :label="1">上架</el-radio>
              <el-radio v-model="form.state" :label="2">下架</el-radio>
            </el-form-item>
            <el-form-item label="图片">
                <!-- <el-input v-model="form.name" style="width:80%;"></el-input> -->
              <el-upload
                ref="upload"
                action="/api/files/upload"
                :on-success="filesUploadSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
                              <!-- action="http://localhost:8888/api/files/upload" -->
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveCom">确 定</el-button>
        </span>
        </el-dialog>
    </div>

  </div>
</template>

<script>
import request from "@/utils/request"
/* 
create初始化，若用户为商家--修改信息，用户为管理员--上下架
*/
export default {
  name: 'ManageCommodity',
  components: {
  },
  data() {
    return {
        loading:false,
        total:1,
        currentPage:1,
        pageSize:10,
        dialogVisible:false,
        form:{},
        user:null,//role:0,//1是商家，非1是管理员
        manger:null,
        tableData: [],
        search: "",
        title:"",
        brands:[],
        categories:[],
        bvalue:'',
        cvalue:'',
        // radio:1,
        // dialogImageUrl: '',
        // dialogVisible2: false,
        url:"",
        srcList:[''],
    }
  },
  created(){
    this.user = this.$store.state.user
    this.manger = this.$store.state.manger
    console.log(' this.$store.state.manger:>> ',this.$store.state.manger );
    if(this.user!=null){  //商家用户
      this.loadUserComInfo()
    }
    if(this.manger!=null){//管理员
      this.loadComInfo()
    }
    if(this.user!=null){
      this.loadBrand()
      this.loadCategory()
    }
  },
  methods: {
    loadComInfo(){
      this.loading=true
      request.get("/commodity/getCom",{
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        // console.log('res :>> ', res);
        this.tableData = res.data.commodity.list
        this.total = res.data.commodity.total
        this.loading=false
      })
    },
    loadUserComInfo(){
      this.loading=true
      request.get("/commodity/getUserCom",{
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search,
          id:this.user.id
        }
      }).then(res => {
        // console.log('res :>> ', res);
        this.tableData = res.data.commodity.list
        this.total = res.data.commodity.total
        this.loading=false
      })
    },
    loadBrand(){
      // console.log('this.user.id :>> ', this.user.id);
      request.get("/brand/getBrand",{
        params:{
          id:this.user.id
        }
      }).then(res =>{
        this.brands = res.data.brands
      })
    },
    loadCategory(){
      request.get("/category/getCategory").then(res =>{
        this.categories = res.data.category
      })
    },
    handleUnBan(row) {
        row.state=1
        request.put("/commodity/updateCommodityInfo",row).then(res => {
        if (res.code=='200'){
            this.$message({
              type: "success",
              message: "上架成功"
            })
          }else {
            this.$message({
              type: "warning",
              message: res.msg
            })
          }
      })
      console.log(row);
    },
    handleBan(row) {
        row.state=2
        request.put("/commodity/updateCommodityInfo",row).then(res => {
        if (res.code=='200'){
            this.$message({
              type: "success",
              message: "下架成功"
            })
          }else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
      })
    },
    add(){
        this.dialogVisible = true
        this.form = {}
        this.bvalue=""
        this.cvalue=""
        this.title="添加新商品"
        /* 清除历史的 */
        this.$nextTick(()=>{
        // 处理未来元素的方法 dom树没加载
          if (this.$refs['upload']){
            this.$refs['upload'].clearFiles();//清楚历史图片
          }
        })
    },
    saveCom(){
      if (this.form.id){//更新
        request.put("/commodity/updateCommodityInfo",this.form).then(res =>{
        console.log(res);
          if (res.code=='200'){
            this.$message({
              type: "success",
              message: "更新成功"
            })
          }else {
            this.$message({
              type: "warning",
              message: res.msg
            })
          }
          this.loadUserComInfo();//刷新表格数据
          this.dialogVisible = false;//关闭弹窗
        });
      }else{
        request.post("commodity/addCommodity",this.form).then(res =>{
          // console.log(res)
          if (res.code=='200'){
            this.$message({
              type: "success",
              message: "添加成功"
            })
          }else {
            this.$message({
              type: "warning",
              message: res.msg
            })
          }
          this.loadUserComInfo();//刷新表格数据
          this.dialogVisible = false;//关闭弹窗
        })  
      }
    },
    handleEdit(row) {
      this.title="修改商品"
      console.log(row);
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.$nextTick(()=>{
        // 处理未来元素的方法 dom树没加载
      if (this.$refs['upload']){
        this.$refs['upload'].clearFiles();//清楚历史图片
      }
      })
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      if(this.user!=null){
          this.loadUserComInfo()
      }else if(this.manger!=null){
        this.loadComInfo()

      }else{
          this.$message({
          type: "warning",
          message: "出错了"
        })
      }
    },
    handleCurrentChange(pageNum){
        this.currentPage = pageNum
      if(this.user!=null){
          this.loadUserComInfo()
      }else if(this.manger!=null){
        this.loadComInfo()

      }else{
          this.$message({
          type: "warning",
          message: "出错了"
        })
      }
    },
    filesUploadSuccess(res){
        // console.log('response :>> ', response);
        console.log('res :>> ', res);
        this.form.image = res.data.url
    },
    // handleRemove(file, fileList) {
    //   console.log(file, fileList);
    // },
    // handlePictureCardPreview(file) {
    //   this.dialogImageUrl = file.url;
    //   this.dialogVisible2 = true;
    // },
    formatData(row, column, cellValue, index){
		//把传过来的日期进行回炉重造一下，又创建了一个js的 Date对象，进行重新构造，转为String字符串
		  // 测试参数含义：不知道参数是什么含义的就打印出来
		  // console.log(row)     	//拿到一行的所有信息，要拿到具体信息,只需要row.XXX 就可以了
		  // console.log(column)  	//拿到列的信息
		  // console.log(cellValue) //拿到单元格数据，拿到时间 2022-03-18T01:46:08.000+00:00
		  // console.log(index)     //拿到索引
      cellValue = cellValue ? cellValue : null;
      let date = new Date(cellValue);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      return Y + M + D;
    },
 },

}
</script>